package com.zr.rocketmq.producer;

import com.zr.rocketmq.entity.Order;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Component
public class TransactionOrderProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private OrderService orderService;

    // 发送事务消息
    public void sendTransactionOrderMessage() {
        // 创建订单
        Order order = new Order();
        String orderId = UUID.randomUUID().toString();
        order.setOrderId(orderId);
        order.setUserId("USER_" + System.currentTimeMillis() % 1000);
        order.setProductId("PROD_" + System.currentTimeMillis() % 100);
        order.setQuantity(1);
        order.setAmount(new BigDecimal("159.99"));
        order.setCreateTime(new Date());
        order.setStatus("PENDING");

        // 构建消息
        Message<Order> message = MessageBuilder
                .withPayload(order)
                .setHeader(RocketMQHeaders.TRANSACTION_ID, orderId)
                .build();

        // 发送事务消息
        rocketMQTemplate.sendMessageInTransaction(
                "order_transaction_topic:pay",
                message, 
                orderId // 额外参数，将传递给事务监听器
        );
        
        log.info("事务消息发送成功，订单ID: {}", orderId);
    }
}
